<?php

namespace Tools\Encryption;

/**
 * AES加密
 * @author kqhenbang
 */
class AesTool
{

    /** @var string AES加密算法 */
    private static $method = 'AES-256-CBC';

    /**
     * 加密
     * @param string $content
     * @param string|null $key
     * @param string|null $iv
     * @return string|false
     * @author kqhenbang
     */
    public static function encrypt(string $content, string $key = null, string $iv = null)
    {
        $secret = substr(openssl_digest(openssl_digest(base64_decode($key), 'sha1', true), 'sha1', true), 0, 64);
        $result = openssl_encrypt($content, self::$method, $secret, 0, $iv);
        return base64_encode($result); //返回结果
    }

    /**
     * 解密
     * @param $content
     * @param string|null $key
     * @param string|null $iv
     * @return false|string
     * @author kqhenbang
     */
    public static function decrypt($content, string $key = null, string $iv = null)
    {
        $content = base64_decode($content);
        $secret = substr(openssl_digest(openssl_digest(base64_decode($key), 'sha1', true), 'sha1', true), 0, 64);
        return openssl_decrypt($content, self::$method, $secret, 0, $iv);
    }
}